# -*- coding: UTF-8 -*-
from django.conf import settings
from django.http import HttpResponse

import time
import uuid
import json

requestObj = object
startTime = 0
reqId = ''


def getTodayDate():
    ticks = time.time()
    localtime = time.localtime(ticks)

    return time.strftime("%Y-%m-%d", localtime)

def getNowTime():
    ticks = time.time()
    localtime = time.localtime(ticks)

    return time.strftime("%H:%M:%S", localtime)

def DLOG(log_content = '', log_level = 'notice', log_name = ''):
    if log_content == '' or log_level == '':
        return

    if log_name == '' and log_level == 'notice' :
        log_name = 'notice'

    log_dir = settings.LOG_DIR
    level = settings.LOG_LEVEL

    if log_level not in level:
        return


    log_file = log_dir + log_name + "." + getTodayDate() + ".log"

    now_time = getNowTime()
    micro_time = "%.4f" % (time.time())

    now_time = str(now_time) + "." + str(micro_time[-4:-1])

    global requestObj

    req_path = requestObj.path
    method = requestObj.method
    META = requestObj.META

    content_prefix = "[" + now_time + " " + META['REMOTE_ADDR'] + " " + method + " " + reqId + " " + log_level + " " + req_path + "] "

    fp = open(log_file, "a+")

    fp.write(content_prefix + log_content + "\n")

    fp.close()
    return

def initReq(request):
    global requestObj, startTime, reqId

    requestObj = request
    startTime = "%.4f" % (time.time())
    reqId = str(uuid.uuid4()).upper()

    reqLog()
    return

def reqLog():
    global requestObj

    method = requestObj.method
    params = json.dumps(requestObj.POST, ensure_ascii=False).decode('utf8')

    params_len = len(params)

    log = "[%s] params: %s len: %d" % (method, params, params_len)

    DLOG(log_content= log, log_level= 'notice', log_name = 'api_notice')

    return

def _response(data):


    if data['errNo'] == "0" :
        data['errMsg'] = "success"
    else:
        if data.has_key('errMsg'):
            data['errMsg'] = data['errMsg']
        else:
            data['errMsg'] = errCode(data['errNo'])

    data['requestId'] = reqId
    res = json.dumps(data, ensure_ascii=False).decode('utf8')

    res_len = len(res)
    endTime = "%.4f" % (time.time())

    runTime = int((float(endTime) - float(startTime)) * 1000)


    log = "res: %s len: %d [runtime = %d ms]" % (res, res_len, runTime)

    DLOG(log_content = log, log_level = 'notice', log_name = 'api_notice')


    return HttpResponse(res, content_type="application/json")

def errCode(code):
    codeData = {
        "0001": "签名校验失败",
        "0002": "请求参数错误",
        "0003": "系统错误"
    }

    return  codeData.has_key(code) and  codeData[code] or "";